package com.farm.authority.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.farm.core.auth.domain.LoginUser;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.authority.domain.Organization;
import com.farm.authority.domain.Post;
import com.farm.authority.domain.Postaction;
import com.farm.authority.domain.User;
import com.farm.authority.domain.Userpost;
import com.farm.authority.dao.OrganizationDaoInter;
import com.farm.authority.dao.PostDaoInter;
import com.farm.authority.dao.PostactionDaoInter;
import com.farm.authority.dao.UserDaoInter;
import com.farm.authority.dao.UserpostDaoInter;
import com.farm.authority.service.OrganizationServiceInter;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.time.TimeTool;
import com.farm.web.easyui.EasyUiTreeNode;

/* *
 *功能：组织机构服务实现类
 *详细：
 *
 *版本：v0.1
 *作者：Farm代码工程自动生成
 *日期：20141122211253
 *说明：
 */
public class OrganizationServiceImpl implements OrganizationServiceInter {
	private OrganizationDaoInter organizationDao;
	private PostDaoInter postDao;
	private UserpostDaoInter userpostDao;
	private PostactionDaoInter postactionDao;
	private UserDaoInter userDao;
//	private static final Logger log = Logger
//			.getLogger(OrganizationServiceImpl.class);

	@Override
	public Organization insertOrganizationEntity(Organization entity,
			LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setMuser(user.getId());
		entity.setUtime(TimeTool.getTimeDate14());
		entity.setState("1");
		if (entity.getParentid() == null) {
			entity.setParentid("NONE");
		}
		entity.setTreecode("NONE");
		entity = organizationDao.insertEntity(entity);
		initTreeCode(entity.getId());
		return entity;
	}

	@Override
	public Organization editOrganizationEntity(Organization entity,
			LoginUser user) {
		Organization entity2 = organizationDao.getEntity(entity.getId());
		entity2.setMuser(user.getId());
		entity2.setUtime(TimeTool.getTimeDate14());
		entity2.setType(entity.getType());
		entity2.setSort(entity.getSort());
		entity2.setState(entity.getState());
		entity2.setComments(entity.getComments());
		entity2.setName(entity.getName());
		organizationDao.editEntity(entity2);
		return entity2;
	}

	@Override
	public void deleteOrganizationEntity(String id, LoginUser user) {
		if (organizationDao.selectEntitys(
				DBRule.addRule(new ArrayList<DBRule>(), "parentid", id, "="))
				.size() > 0) {
			throw new RuntimeException("不能删除该节点，请先删除其子节点");
		}
		// 删除岗位
		for (Post post : postDao.selectEntitys(DBRule.addRule("ORGANIZATIONID",
				id, "="))) {
			deletePostEntity(post.getId(), user);
		}
		// 删除组织机构
		organizationDao.deleteEntity(organizationDao.getEntity(id));
	}

	@Override
	public Organization getOrganizationEntity(String id) {
		if (id == null) {
			return null;
		}
		return organizationDao.getEntity(id);
	}

	@Override
	public DataQuery createOrganizationSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery
				.init(query, "ALONE_AUTH_ORGANIZATION",
						"ID,TYPE,SORT,PARENTID,MUSER,CUSER,STATE,UTIME,CTIME,COMMENTS,NAME,TREECODE");
		return dbQuery;
	}

	@Override
	public void deletePostEntity(String id, LoginUser user) {
		// 同时删除岗位用户
		userpostDao.deleteEntitys(DBRule.addRule("POSTID", id, "="));
		// 同时删除岗位权限
		postactionDao.deleteEntitys(DBRule.addRule("POSTID", id, "="));
		postDao.deleteEntity(postDao.getEntity(id));
	}

	@Override
	public Post getPostEntity(String id) {
		if (id == null) {
			return null;
		}
		return postDao.getEntity(id);
	}

	@Override
	public DataQuery createPostSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery
				.init(
						query,
						"ALONE_AUTH_POST",
						"ID,TYPE,NAME,ORGANIZATIONID,PSTATE,EUSER,EUSERNAME,CUSER,CUSERNAME,ETIME,CTIME");
		return dbQuery;
	}

	@Override
	public void moveOrgTreeNode(String orgId, String targetOrgId) {
		// 移动节点
		Organization node = getOrganizationEntity(orgId);
		if (node.getParentid().equals("NONE")) {
			throw new RuntimeException("不能够移动根节点!");
		}
		Organization target = getOrganizationEntity(targetOrgId);
		if (target.getTreecode().indexOf(node.getTreecode()) >= 0) {
			throw new RuntimeException("不能够移动到其子节点下!");
		}
		node.setParentid(targetOrgId);
		organizationDao.editEntity(node);
		// 构造所有树TREECODE
		List<Organization> list = organizationDao.getAllSubNodes(orgId);
		for (Organization org : list) {
			initTreeCode(org.getId());
		}
	}

	private void initTreeCode(String treeNodeId) {
		Organization node = getOrganizationEntity(treeNodeId);
		if (node.getParentid().equals("NONE")) {
			node.setTreecode(node.getId());
		} else {
			node.setTreecode(organizationDao.getEntity(node.getParentid())
					.getTreecode()
					+ node.getId());
		}
		organizationDao.editEntity(node);
	}

	@Override
	public Post editPost(String postId, String postname, String posttype,
			LoginUser user) {
		Post post = postDao.getEntity(postId);
		post.setName(postname);
		post.setType(posttype);
		post.setEtime(TimeTool.getTimeDate14());
		post.setEuser(user.getId());
		post.setEusername(user.getName());
		postDao.editEntity(post);
		return post;
	}

	@Override
	public Post insertPost(String orgId, String postname, String posttype,
			LoginUser user) {
		Post post = new Post();
		post.setName(postname);
		post.setType(posttype);
		post.setCtime(TimeTool.getTimeDate14());
		post.setCuser(user.getId());
		post.setCusername(user.getName());
		post.setEtime(TimeTool.getTimeDate14());
		post.setEuser(user.getId());
		post.setEusername(user.getName());
		post.setOrganizationid(orgId);
		post.setPstate("1");
		return postDao.insertEntity(post);
	}

	@Override
	public List<EasyUiTreeNode> loadPostTree(String ids) {
		if (ids == null || ids.trim().length() <= 0) {
			ids = "NONE";
		}
		DataQuery query = DataQuery
				.getInstance(
						"1",
						"NAME,PARENTID,ID,UTYPE",
						"(SELECT NAME,PARENTID,ID,'11' AS UTYPE,SORT FROM alone_auth_organization  UNION SELECT NAME,ORGANIZATIONID AS PARENTID,ID,TYPE AS UTYPE,1000 as SORT FROM alone_auth_post  ) a ");
		query.setPagesize(1000);
		query.addRule(new DBRule("PARENTID", ids, "="));
		query.setNoCount();
		query.addSort(new DBSort("UTYPE", "asc"));
		query.addSort(new DBSort("SORT", "asc"));
		DataQuery query2 = DataQuery
				.getInstance(
						"1",
						"a.NAME as NAME,a.PARENTID as PARENTID,a.ID as ID,a.UTYPE as UTYPE",
						"alone_auth_organization b LEFT JOIN (SELECT NAME,PARENTID,ID,'0' AS UTYPE FROM alone_auth_organization  UNION SELECT NAME,ORGANIZATIONID AS PARENTID,ID,TYPE AS UTYPE FROM alone_auth_post  ) a ON a.PARENTID=b.ID");
		query2.setPagesize(1000);
		query2.addRule(new DBRule("b.PARENTID", ids, "="));
		query2.setNoCount();
		List<EasyUiTreeNode> list = null;
		try {
			List<Map<String, Object>> listOne = query.search().getResultList();
			for (Map<String, Object> node : listOne) {
				if (node.get("UTYPE").equals("1")) {
					node.put("UTYPE", "icon-suppliers");
				}
				if (node.get("UTYPE").equals("2")) {
					node.put("UTYPE", "icon-user_medical");
				}
			}
			list = EasyUiTreeNode.formatAsyncAjaxTree(listOne, query2.search()
					.getResultList(), "PARENTID", "ID", "NAME", "UTYPE");
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return list;
	}

	@Override
	public void addUserPost(String userId, String postId, LoginUser currentUser) {
		User user = userDao.getEntity(userId);
		if (user.getState().equals("2")) {
			throw new RuntimeException("该用户已经删除");
		}
		Post post = postDao.getEntity(postId);
		if (post == null) {
			throw new RuntimeException("请选择正确的岗位");
		}
		// 先判断岗位是否标准岗1:标准2:临时
		if (post.getType().equals("1")) {
			// 标准，清理掉用户其他的标准岗
			for (Userpost userpost : userpostDao.getStandardUserPost(userId)) {
				userpostDao.deleteEntity(userpost);
			}
		}
		for (Userpost userpost : userpostDao.getTempUserPost(userId)) {
			if (userpost.getUserid().equals(userId)
					&& userpost.getPostid().equals(postId)) {
				return;
			}
		}
		// 添加岗位
		Userpost userpost = new Userpost();
		userpost.setOrganizationid(post.getOrganizationid());
		userpost.setPostid(postId);
		userpost.setUserid(userId);
		userpostDao.insertEntity(userpost);
	}

	// ----------------------------------------------------------------------------------
	public OrganizationDaoInter getOrganizationDao() {
		return organizationDao;
	}

	public void setOrganizationDao(OrganizationDaoInter dao) {
		this.organizationDao = dao;
	}

	public PostDaoInter getPostDao() {
		return postDao;
	}

	public PostactionDaoInter getPostactionDao() {
		return postactionDao;
	}

	public void setPostactionDao(PostactionDaoInter postactionDao) {
		this.postactionDao = postactionDao;
	}

	public void setPostDao(PostDaoInter postDao) {
		this.postDao = postDao;
	}

	public UserpostDaoInter getUserpostDao() {
		return userpostDao;
	}

	public void setUserpostDao(UserpostDaoInter userpostDao) {
		this.userpostDao = userpostDao;
	}

	public UserDaoInter getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDaoInter userDao) {
		this.userDao = userDao;
	}

	@Override
	public void removePostUsers(String postId, String userid,
			LoginUser currentUser) {
		userpostDao.deleteEntitys(DBRule.addRule(DBRule.addRule("USERID",
				userid, "="), "POSTID", postId, "="));
	}

	@Override
	public void setPostActionTree(List<String> actionTreeIds, String postId) {
		if (postId == null || postId.trim().length() <= 0) {
			throw new IllegalArgumentException("请选择一个岗位");
		}
		// 删除之前的菜单
		postactionDao.deleteEntitys(DBRule.addRule("POSTID", postId, "="));
		for (String nodeId : actionTreeIds) {
			Postaction postaction = new Postaction();
			postaction.setMenuid(nodeId);
			postaction.setPostid(postId);
			postactionDao.insertEntity(postaction);
		}
	}

}